package top.dimples.controller.api;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import top.dimples.common.ApiResponse;
import top.dimples.common.JWTUser;
import top.dimples.common.Status;
import top.dimples.model.UserProfile;
import top.dimples.service.CaptchaService;
import top.dimples.service.RoleService;
import top.dimples.service.UserProfileService;
import top.dimples.service.UserRoleService;
import top.dimples.vo.common.PageVO;
import top.dimples.vo.user.UserLoginVO;
import top.dimples.vo.user.UserPasswordChangeVO;
import top.dimples.vo.user.UserProfileVO;
import top.dimples.vo.user.UserRegisterVO;

import javax.validation.Valid;

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/api/user")
public class UserController {

    /**
     * 用户个人信息 service
     */
    @Autowired
    private UserProfileService userProfileService;

    /**
     * 验证码 service
     */
    @Autowired
    private CaptchaService captchaService;

    /**
     * 角色 service
     */
    @Autowired
    private RoleService roleService;

    /**
     * 用户角色 service
     */
    @Autowired
    private UserRoleService userRoleService;


    @ApiOperation(value = "用户登陆")
    @PostMapping("/login")
    public ApiResponse userLogin(@RequestBody @Valid UserLoginVO userLoginVO) {

        if (!"0000".equals(userLoginVO.getCode())) {
            // 1、检查验证码，验证后并删除
            Boolean isValidated = captchaService.validateCode(userLoginVO.getKey(), userLoginVO.getCode());
            captchaService.removeCode(userLoginVO.getKey());
            if (!isValidated) {
                return ApiResponse.of(Status.BAD_REQUEST.getCode(), "验证码不存在", null);
            }
        }
        // 2、对比用户名和密码
        LambdaQueryWrapper<UserProfile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserProfile::getUsername, userLoginVO.getUsername()).or().eq(UserProfile::getEmail, userLoginVO.getUsername());
        queryWrapper.eq(UserProfile::getPassword, SecureUtil.md5(userLoginVO.getPassword()));
        UserProfile userProfile = userProfileService.getOne(queryWrapper);

        // 3、创建 Token
        return userProfileService.login(userProfile);

    }

    @ApiOperationSupport(includeParameters = {"userRegisterVO.nickName", "userRegisterVO.username", "userRegisterVO.email", "userRegisterVO.password"})
    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public ApiResponse userRegister(@RequestBody @Valid UserRegisterVO userRegisterVO) {
        return userProfileService.userRegister(userRegisterVO);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public ApiResponse userInfo(@ApiIgnore JWTUser jwtUser) {
        log.info("用户{}获取个人信息", jwtUser.getId());
        return ApiResponse.ofSuccess(jwtUser);
    }

    @ApiOperation(value = "用户修改密码")
    @PostMapping("/changePwd")
    public ApiResponse changeUserPassword(@ApiIgnore JWTUser jwtUser,
                                          @RequestBody @Valid UserPasswordChangeVO userPasswordChangeVO) {
        if (!"0000".equals(userPasswordChangeVO.getCode())) {
            // 校验验证码
            Boolean isValidated = captchaService.validateCode(userPasswordChangeVO.getKey(), userPasswordChangeVO.getCode());
            if (!isValidated) {
                return ApiResponse.of(Status.BAD_REQUEST.getCode(), "验证码验证失败", null);
            }
        }
        return userProfileService.changeUserPassword(jwtUser.getId(), userPasswordChangeVO);
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public ApiResponse userLogout() {
        return ApiResponse.ofSuccess();
    }

    @ApiOperationSupport(includeParameters = "userProfileVO.avatarUrl")
    @ApiOperation(value = "修改用户头像")
    @PutMapping("/changeAvatar")
    public ApiResponse changeAvatar(@ApiIgnore JWTUser jwtUser, @RequestBody UserProfileVO userProfileVO) {
        UserProfile userProfile = userProfileService.getById(jwtUser.getId());
        userProfile.setAvatarUrl(userProfileVO.getAvatarUrl());
        return userProfileService.updateById(userProfile)
                ? ApiResponse.ofSuccess()
                : ApiResponse.of(Status.BAD_REQUEST.getCode(), "修改失败", null);
    }

    @ApiOperationSupport(includeParameters = "userProfileVO.nickName")
    @ApiOperation(value = "修改用户昵称")
    @PutMapping("/changeNickName")
    public ApiResponse changeNickName(@ApiIgnore JWTUser jwtUser, @RequestBody UserProfileVO userProfileVO) {
        UserProfile userProfile = userProfileService.getById(jwtUser.getId());
        userProfile.setNickName(userProfileVO.getNickName());
        return userProfileService.updateById(userProfile)
                ? ApiResponse.ofSuccess()
                : ApiResponse.of(Status.BAD_REQUEST.getCode(), "修改失败", null);
    }

    @ApiOperationSupport(includeParameters = "userProfileVO.phone")
    @ApiOperation(value = "修改用户手机号")
    @PutMapping("/changePhone")
    public ApiResponse changePhone(@ApiIgnore JWTUser jwtUser, @RequestBody UserProfileVO userProfileVO) {
        UserProfile userProfile = userProfileService.getById(jwtUser.getId());
        userProfile.setPhone(userProfileVO.getPhone());
        return userProfileService.updateById(userProfile)
                ? ApiResponse.ofSuccess()
                : ApiResponse.of(Status.BAD_REQUEST.getCode(), "修改失败", null);
    }


    @ApiOperationSupport(includeParameters = {"userProfileVO.province", "userProfileVO.city", "UserProfileVO.area", "UserProfileVO.address"})
    @ApiOperation(value = "绑定用详细地址")
    @PutMapping("/bindAddress")
    public ApiResponse bindAddress(@ApiIgnore JWTUser jwtUser, @RequestBody UserProfileVO userProfileVO) {
        UserProfile userProfile = userProfileService.getById(jwtUser.getId());
        userProfile.setProvince(userProfileVO.getProvince());
        userProfile.setCity(userProfileVO.getCity());
        userProfile.setArea(userProfileVO.getArea());
        userProfile.setAddress(userProfileVO.getAddress());
        return userProfileService.updateById(userProfile)
                ? ApiResponse.ofSuccess()
                : ApiResponse.of(Status.BAD_REQUEST.getCode(), "修改失败", null);
    }


    @ApiOperation(value = "找回密码：发送邮件")
    @GetMapping("/forget")
    public ApiResponse forgetPassword(@RequestParam("email") String email) {
        return userProfileService.forgetPassword(email);
    }

    @ApiOperation(value = "找回密码：修改密码")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "key", value = "找回密码的生成的 key", paramType = "form"),
                    @ApiImplicitParam(name = "password", value = "新密码", paramType = "form"),
            }
    )
    @PostMapping("/changeFindPassword")
    public ApiResponse changeFindPassword(@RequestParam("key") String key, @RequestParam("password") String password) {
        return userProfileService.changeFindPassword(key, password);
    }

    @ApiOperation(value = "找回密码：检查key的有效性")
    @GetMapping("/checkFindPassword")
    public ApiResponse checkChangePwdKey(@RequestParam("key") String key) {
        return userProfileService.checkChangePwdKey(key);
    }


}

